import {Image, StyleSheet, View, Text, TouchableOpacity, TextInput, ScrollView, Modal, FlatList} from 'react-native';
import {Stack, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';;
import React, {useEffect, useRef, useState} from "react";
import addIcon from "@/assets/images/releaseImg/addIcon.png"
import addTagGroupIcon from "@/assets/images/releaseImg/addTagGroupIcon.png"
import * as ImagePicker from "expo-image-picker";
import {loadingService} from "@/utils/loadingServer";
import {getToken, validatePhoneNumber} from "@/utils";
import axios from "axios/index";
import {api, txApiKey} from "@/config/config-params";
import { setRegisterGroupData, setActivityTypeObj, initRegisterGroupData } from "@/store/slices/registerGroupSlice"
import {showToast} from "@/utils/rootToast";
import { useDispatch, useSelector } from "react-redux"
import {RootState} from "@/store";
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import SingleOickerModal from "@/components/SinglePickerModal";
import {getActivityTypeList, postCommunityGroupByItemRequest} from "@/services/releaseServices";
import searchIcon from "@/assets/images/releaseImg/searchIcon.png";
import MapView, {Marker} from "react-native-maps";
import addressCheck from "@/assets/images/releaseImg/adressCheck.png";
import createActivityCloseBtn from "@/assets/images/activityImg/createActivityCloseBtn.png";


export default function registerGroupScreen() {

    const router = useRouter();
    const dispatch = useDispatch();
    const registerGroup  = useSelector((state: RootState) => state.registerGroup);

    const [showSelectTag, setShowSelectTag] = useState(false);
    const [currentTag, setCurrentTag] = useState("");
    const [showActivityType, setShowActivityType] = useState(false);
    const [typeList, setTypeList] = useState([]);
    const [selectActivityType, setSelectActivityType] = useState(typeList[0]?.value || "");
    const [selectTypeIndex, setSelectTypeIndex] = useState(0);
    const [tempSelectTypeAll, setTempSelectTypeAll] = useState<any>({});
    const [showSearchModal, setShowSearchModal] = useState(false);
    const [activeAdress, setActiveAdress] = useState(0);
    const [mapKey, setMapKey] = useState(1);
    const [cityList, setCityList] = useState([]);
    const [region, setRegion] = useState({
        latitude: 23.114155,
        longitude: 113.318977,
        latitudeDelta: 0.0912,
        longitudeDelta: 0.0921,
    });
    const [searchTitle, setSearchTitle] = useState("");
    const [isVisialMap, setIsVisialMap] = useState(true);

    const searchInptRef = useRef(null);

    useEffect(() => {
        if (registerGroup.registerStatus == 'create') {
            dispatch(initRegisterGroupData())
        };

        setTimeout(() => {
            if (registerGroup?.activityTypeObj) {
                setSelectActivityType(registerGroup.activityTypeObj?.val);
                setSelectTypeIndex(registerGroup.activityTypeObj?.index);
            };

        }, 1000)
    }, [])

    const pickImage = async () => {
        // Request media library permissions
        let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();

        if (permissionResult.granted === false) {
            alert('Permission to access the media library is required!');
            return;
        }

        // Open image picker
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            // allowsEditing: true,
            // aspect: [4, 3],
            quality: 1,
        });

        if (!result.canceled) {
            const formData = new FormData();
            formData.append('img', {
                uri: result.assets[0].uri,
                type: result.assets[0].type, // mime 类型，例如 'image/jpeg'
                name: result.assets[0].fileName, // 图片名称
            });

            loadingService.show();

            const token = await getToken();
            loadingService.show();

            try {
                const response = await axios.post(`${api}/social/uploadImg`, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        "Authorization": token,
                    },
                });
                if (response?.data.code == 200) {
                    // loadingService.hide();
                    // const imgList = [...createActive.inputData.imgUrls, response.data.data.url];
                    const coverUrl = response.data.data.url;
                    dispatch(setRegisterGroupData({ coverUrl: coverUrl }))
                    // setAvatorImg(response.data.data.url)
                } else {
                    showToast(response?.data.msg)
                };

                loadingService.hide();
            } catch (error) {
                console.error('上传失败：', error);
                loadingService.hide();
            }
        }
    };

    const changeGroupDataByItem = function (key: string, value: string) {
        dispatch(setRegisterGroupData({ [key]: value }))
    };

    const pushTag = function () {
        const list = [...registerGroup?.registerGroupData?.tags, currentTag];
        setCurrentTag("");
        dispatch(setRegisterGroupData({ tags: list }))
        setShowSelectTag(false)
    };

    useEffect(() => {
        getActivityTypeList()
            .then(res => {
                const itemEach = res.data?.typeList;
                const list = [];
                itemEach.forEach((item: any, index: number) => {
                    const obj = {
                        label: item.name,
                        value: item.id,
                    };
                    list.push(obj);
                })
                setTypeList(list)
            })
            .catch(err => {
                console.log('err', err);
            })
    }, [])

    const resetSelectTypeAll = function () {
        setSelectTypeIndex(tempSelectTypeAll?.index || 0);
        setSelectActivityType(tempSelectTypeAll.id || typeList[0].id);
    };

    const getMapByTitleRequest = function (title?: string) {
        axios.get(`https://apis.map.qq.com/ws/place/v1/suggestion?key=${txApiKey}&keyword=${title}`)
            .then(res => {
                setCityList(res.data?.data);
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    const searchByKeyword = function (val: string) {
        setSearchTitle(val);
    };

    const searchByTitle = function () {
        if (searchTitle == '') return showToast("请输入搜索内容！");
        getMapByTitleRequest(searchTitle)
    };

    const buildMap = function (index, item) {
        setActiveAdress(index)
        const location = item.location;

        setMapKey(mapKey + 1); // 改变 key 强制刷新
        dispatch(setRegisterGroupData({ currentLocation: item }))
        setRegion({
            latitude: location.lat,
            longitude: location.lng,
            latitudeDelta: 0.0022,
            longitudeDelta: 0.0021,
        })
    };

    const cityReaderItem = function ({ item, index }) {
        return (
            <TouchableOpacity onPress={() => buildMap(index, item)}>
                <View style={styles.locationItem}>
                    <View style={{ width: 320}}>
                        <Text style={styles.locationTitle}>{ item?.title }</Text>
                        <Text style={styles.locationDescription}>{ item?.address }</Text>
                    </View>
                    {
                        activeAdress == index && (
                            <View style={styles.adressIcon}>
                                <Image source={addressCheck} style={{ width: "100%", height: "100%" }} />
                            </View>
                        )
                    }
                </View>
            </TouchableOpacity>
        )
    };

    const groupCard = function () {
        router.push("/registerGroup/card")
    };

    const goBindGroup = function () {
        router.push("/registerGroup/bindGroup")
    };

    const pickImageImageList = async () => {
        // Request media library permissions
        let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();

        if (permissionResult.granted === false) {
            alert('Permission to access the media library is required!');
            return;
        }

        // Open image picker
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            // allowsEditing: true,
            // aspect: [4, 3],
            quality: 1,
        });

        if (!result.canceled) {
            const formData = new FormData();
            formData.append('img', {
                uri: result.assets[0].uri,
                type: result.assets[0].type, // mime 类型，例如 'image/jpeg'
                name: result.assets[0].fileName, // 图片名称
            });

            loadingService.show();

            const token = await getToken();
            loadingService.show();

            try {
                const response = await axios.post(`${api}/social/uploadImg`, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        "Authorization": token,
                    },
                });
                if (response?.data.code == 200) {
                    loadingService.hide();
                    const imgList = [...registerGroup?.registerGroupData?.imgUrls, response.data.data.url];
                    dispatch(setRegisterGroupData({ imgUrls: imgList }))
                    // setAvatorImg(response.data.data.url)
                } else {
                    showToast(response?.data.msg)
                };

                loadingService.hide();
            } catch (error) {
                console.error('上传失败：', error);
                loadingService.hide();
            }


        }
    };

    const removeImage = function (index: number) {
        const list = [];
        registerGroup?.registerGroupData?.imgUrls.forEach((item: any, idx: number) => {
            if (index !== idx) {
                list.push(item);
            };
        })
        dispatch(setRegisterGroupData({ imgUrls: list }))
    };

    const applyGroup = function () {
        const {
            coverUrl,
            currentLocation,
            announcement,
            tags,
            cardTitleTemplate,
            contact,
            introduce,
            imgUrls,
            founderIntroduce,
            activityIntroduce,
            requirement,
            name,
            parentId
        } = registerGroup?.registerGroupData;

        if (!coverUrl) {
            return showToast("请上传社群封面");
        };

        if (!name) {
            return showToast("请填写社群名称");
        };

        if (!selectActivityType) {
            return showToast("请选择活动类型");
        };

        if (!currentLocation) {
            return showToast("请添加活动地址");
        };

        if (!announcement) {
            return showToast("请填写社群公告");
        };

        if (tags.length <= 0) {
            return showToast("至少填写一个社群标签");
        };

        // //关联总群未写
        // if (tags.length <= 0) {
        //     return showToast("请填写社群标签");
        // };

        if (cardTitleTemplate.length <= 0) {
            return showToast("请填写社群标签");
        };

        if (!validatePhoneNumber(contact)) {
            return showToast("请输入正确联系方式");
        };

        if (!announcement) {
            return showToast("请填写社群介绍");
        };

        if (imgUrls.length <= 0) {
            return showToast("至少上传一张社群图片");
        };

        if (!founderIntroduce) {
            return showToast("请填写创始人简介");
        };

        if (!activityIntroduce) {
            return showToast("请填写活动简介");
        };

        if (!requirement) {
            return showToast("请填写加入资格");
        };

        const cardTitleTemplateList = cardTitleTemplate.map((item: any) => {
            return item.title
        });

        const data = {
            coverUrl,
            name,
            "typeId": typeList[selectTypeIndex]?.value,
            "destName": registerGroup?.registerGroupData?.currentLocation?.title,
            "destLongitude": registerGroup?.registerGroupData?.currentLocation.location?.lng,
            "destLatitude": registerGroup?.registerGroupData?.currentLocation.location?.lat,
            announcement,
            tags,
            parentId: parentId?.parentId,
            cardTitleTemplate: cardTitleTemplateList,
            contact,
            introduce,
            imgUrls,
            founderIntroduce,
            activityIntroduce,
            requirement
        };
        loadingService.show()
        postCommunityGroupByItemRequest(data)
            .then(res => {
                loadingService.hide()
                router.push("/createActivity/createActivitySuccess/0")
                console.log("res", res);
            })
            .catch(err => {
                loadingService.hide()
                console.log('err', err);
            })

    };

    const activiyBtn = function () {
        const {
            coverUrl,
            currentLocation,
            announcement,
            tags,
            cardTitleTemplate,
            contact,
            introduce,
            imgUrls,
            founderIntroduce,
            activityIntroduce,
            requirement,
            name
        } = registerGroup?.registerGroupData;
        const bol = coverUrl &&
            name &&
            selectActivityType &&
            currentLocation &&
            announcement &&
            tags.length > 0 &&
            cardTitleTemplate?.length > 0 &&
            contact &&
            introduce &&
            imgUrls.length > 0 &&
            founderIntroduce &&
            activityIntroduce &&
            requirement
        return bol;
    };

    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '登记社群', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#f7f7f7', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                }}
            />
            <KeyboardAwareScrollView
                style={styles.scrollView}
                contentContainerStyle={styles.scrollViewContent}
                keyboardShouldPersistTaps="handled"
                extraScrollHeight={80} // 调整额外滚动高度，确保不会被键盘遮挡
            >
                <ScrollView style={{ flex: 1, }}>
                    <View style={styles.registerGroupContainer}>
                        <TouchableOpacity onPress={pickImage}>
                            <View style={styles.registerGroupInfo}>
                                <TouchableOpacity>
                                    {
                                        registerGroup?.registerGroupData?.coverUrl ? (
                                            <View style={styles.CoverImgWrap}>
                                                <Image source={{ uri: registerGroup?.registerGroupData?.coverUrl}} style={{ width: "100%", height: "100%" }}  />
                                            </View>

                                        ) : (
                                            <View style={styles.avatorGroup}>
                                                <View style={styles.addIcon}>
                                                    <Image source={addIcon} style={{ width: "100%", height: "100%" }}  />
                                                </View>
                                            </View>
                                        )
                                    }
                                </TouchableOpacity>
                                <View style={{ flex: 1, marginLeft: 10 }}>
                                    <Text>社群封面</Text>
                                </View>
                                <TouchableOpacity onPress={pickImage}>
                                    <View style={styles.registerHeaderSetting}>
                                        <Text style={styles.settingTitle}>设置社群封面</Text>
                                        <AntDesign name="right" size={12} color="#9C9EAC" />
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </TouchableOpacity>

                        <View style={styles.registerContent}>
                            <View style={styles.registerItem}>
                                <Text>社群名称</Text>
                                <TextInput
                                    placeholder="请输入"
                                    onChangeText={(val) => changeGroupDataByItem("name", val)}
                                    value={registerGroup?.registerGroupData?.name}
                                />
                            </View>
                           <TouchableOpacity onPress={() => {
                               setShowActivityType(true)
                               const obj = { id: selectActivityType, index: selectTypeIndex }
                               setTempSelectTypeAll(obj);
                           }}>
                               <View style={styles.registerItem}>
                                   <Text>社群类型</Text>
                                   <View style={styles.selectItem}>
                                       <Text style={styles.selectItemText}>
                                           { selectActivityType && typeList.length > 0 ? typeList[selectTypeIndex]?.label  : "请选择" }
                                       </Text>
                                       <AntDesign name="right" size={12} color="#9C9EAC" />
                                   </View>
                               </View>
                           </TouchableOpacity>
                            <TouchableOpacity onPress={() => setShowSearchModal(true)}>
                                <View style={styles.registerItem}>
                                    <Text>社群地点</Text>
                                    {
                                        registerGroup?.registerGroupData?.currentLocation?.title ? (
                                            <View style={styles.selectItem}>
                                                <Text style={styles.selectItemText}>{ registerGroup?.registerGroupData?.currentLocation?.title }</Text>
                                            </View>
                                        ) : (
                                            <View style={styles.selectItem}>
                                                <Text style={styles.selectItemText}>
                                                    请选择
                                                </Text>
                                                <AntDesign name="right" size={12} color="#9C9EAC" />
                                            </View>
                                        )
                                    }

                                </View>
                            </TouchableOpacity>
                            <View style={styles.registerItem}>
                                <Text>社群公告</Text>
                                <TextInput
                                    placeholder="请输入"
                                    onChangeText={(val) => changeGroupDataByItem("announcement", val)}
                                    value={registerGroup?.registerGroupData?.announcement}
                                />
                            </View>
                            <View style={styles.registerItemContainer}>
                                <View style={styles.registerTagWrap}>
                                    <Text>社群标签<Text style={styles.tagText}>(最多3个标签，每个8个字以内)</Text></Text>
                                    <TouchableOpacity onPress={() => setShowSelectTag(true)}>
                                        <View style={{ width: 19, height: 19 }}>
                                            <Image source={addTagGroupIcon} style={{ width: "100%", height: "100%" }}/>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                                <View style={styles.tagList}>
                                    {
                                        registerGroup?.registerGroupData?.tags?.map((item: any, index: number) => {
                                            return (
                                                <View style={styles.tagListItem} key={index}>
                                                    <Text style={styles.tagListItemText}>{ item }</Text>
                                                </View>
                                            )
                                        })
                                    }
                                </View>
                            </View>
                            <TouchableOpacity onPress={goBindGroup}>
                                <View style={styles.registerItem}>
                                    <Text>关联总群</Text>
                                    <View style={styles.selectItem}>
                                        {
                                            registerGroup?.registerGroupData?.parentId?.title && (
                                                <Text style={styles.selectItemText}>
                                                    { registerGroup?.registerGroupData?.parentId?.title }
                                                </Text>
                                            )
                                        }
                                        {
                                            !registerGroup?.registerGroupData?.parentId?.title && (
                                                <Text style={styles.selectItemText}>
                                                    去关联
                                                </Text>
                                            )
                                        }
                                        <AntDesign name="right" size={12} color="#9C9EAC" />
                                    </View>
                                </View>
                            </TouchableOpacity>

                            <TouchableOpacity onPress={groupCard}>
                                <View style={styles.registerItem}>
                                    <Text>群名片模板</Text>
                                    {
                                        registerGroup?.registerGroupData?.cardTitleTemplate?.length > 0 ? (
                                            <View style={styles.selectItem}>
                                                <Text style={styles.selectItemText}>
                                                    已选择
                                                </Text>
                                                <AntDesign name="right" size={12} color="#9C9EAC" />
                                            </View>
                                        ) : (
                                            <View style={styles.selectItem}>
                                                <Text style={styles.selectItemText}>
                                                    去选择
                                                </Text>
                                                <AntDesign name="right" size={12} color="#9C9EAC" />
                                            </View>
                                        )
                                    }

                                </View>
                            </TouchableOpacity>

                            <View style={styles.registerItem}>
                                <Text>联系方式</Text>
                                <TextInput
                                    placeholder="请输入"
                                    onChangeText={(val) => changeGroupDataByItem("contact", val)}
                                    value={registerGroup?.registerGroupData?.contact}
                                />
                            </View>
                        </View>
                        <View style={styles.registerInputTextWrap}>

                            <View style={styles.resisterInputTextItem}>
                                <View>
                                    <Text>社群介绍</Text>
                                </View>
                                <View style={styles.resisterInputTextItemText}>
                                    <TextInput
                                        multiline={true}
                                        placeholder='请输入社群介绍'
                                        style={{ width: "100%", fontSize: 12, height: "100%" }}
                                        onChangeText={(val) => changeGroupDataByItem("introduce", val)}
                                        value={registerGroup?.registerGroupData?.introduce}
                                    />
                                </View>
                            </View>

                            <View style={styles.resisterInputTextItem}>
                                <View>
                                    <Text>社群图片</Text>
                                </View>

                                <View style={styles.addPicContainer}>
                                    <ScrollView
                                        horizontal={true}
                                        showsHorizontalScrollIndicator={false}
                                    >
                                        {
                                            registerGroup?.registerGroupData?.imgUrls?.length > 0 && registerGroup?.registerGroupData?.imgUrls?.map((item: any, index: number) => {
                                                return (
                                                    <TouchableOpacity activeOpacity={1}>
                                                        <View style={styles.addPic}>
                                                            <Image source={{ uri: item }} style={{ width: "100%", height: "100%" }} />
                                                            <TouchableOpacity style={styles.imgCloseWrap} onPress={() => removeImage(index)}>
                                                                <Image source={createActivityCloseBtn} style={{ width: "100%", height: "100%" }}/>
                                                            </TouchableOpacity>
                                                        </View>
                                                    </TouchableOpacity>
                                                )
                                            })
                                        }

                                        {
                                            registerGroup?.registerGroupData?.imgUrls?.length <= 9 && (
                                                <TouchableOpacity onPress={pickImageImageList}>
                                                    <View style={styles.addPic}>
                                                        <View style={styles.addIcon}>
                                                            <Image source={addIcon} style={{ width: "100%", height: "100%" }} />
                                                        </View>
                                                    </View>
                                                </TouchableOpacity>
                                            )
                                        }
                                    </ScrollView>

                                </View>

                                {/*<TouchableOpacity>*/}
                                {/*    <View style={styles.groupImage}>*/}
                                {/*        <View style={{ width: 18, height: 18, }}>*/}
                                {/*            <Image source={addIcon} style={{ width: "100%", height: "100%"}} />*/}
                                {/*        </View>*/}
                                {/*    </View>*/}
                                {/*</TouchableOpacity>*/}
                            </View>

                            <View style={styles.resisterInputTextItem}>
                                <View>
                                    <Text>创始人简介</Text>
                                </View>
                                <View style={styles.resisterInputTextItemText}>
                                    <TextInput
                                        multiline={true}
                                        placeholder='请输入创始人简介'
                                        style={{ width: "100%", fontSize: 12, height: "100%" }}
                                        onChangeText={(val) => changeGroupDataByItem("founderIntroduce", val)}
                                        value={registerGroup?.registerGroupData?.founderIntroduce}
                                    />
                                </View>
                            </View>

                            <View style={styles.resisterInputTextItem}>
                                <View>
                                    <Text>活动简介</Text>
                                </View>
                                <View style={styles.resisterInputTextItemText}>
                                    <TextInput
                                        multiline={true}
                                        placeholder='请输入活动简介'
                                        style={{ width: "100%", fontSize: 12, height: "100%" }}
                                        onChangeText={(val) => changeGroupDataByItem("activityIntroduce", val)}
                                        value={registerGroup?.registerGroupData?.activityIntroduce}
                                    />
                                </View>
                            </View>

                            <View style={styles.resisterInputTextItem}>
                                <View>
                                    <Text>加入资格</Text>
                                </View>
                                <View style={styles.resisterInputTextItemText}>
                                    <TextInput
                                        multiline={true}
                                        placeholder='请输入加入资格'
                                        style={{ width: "100%", fontSize: 12, height: "100%" }}
                                        onChangeText={(val) => changeGroupDataByItem("requirement", val)}
                                        value={registerGroup?.registerGroupData?.requirement}
                                    />
                                </View>
                            </View>
                        </View>
                    </View>
                </ScrollView>
                {
                    !activiyBtn() && (
                        <TouchableOpacity onPress={applyGroup}>
                            <View style={styles.footerBtnWrap}>
                                <View style={styles.footerBtn}>
                                    <Text style={styles.footerBtnText}>申请社群</Text>
                                </View>
                            </View>
                        </TouchableOpacity>
                    )
                }

                {
                    activiyBtn() && (
                        <TouchableOpacity onPress={applyGroup}>
                            <View style={styles.footerBtnWrapActive}>
                                <View style={styles.footerBtnActive}>
                                    <Text style={styles.footerBtnTextActive}>申请社群</Text>
                                </View>
                            </View>
                        </TouchableOpacity>
                    )
                }


                <Modal
                    animationType="fade"
                    transparent={true}
                    visible={showSelectTag}
                >
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={(event) => {
                            if (event.target === event.currentTarget) {
                                setShowSelectTag(false);
                            }
                        }}
                        style={styles.becameModelContainer}
                    >
                        <View style={styles.becameModelWrap}>
                            <View style={styles.becameModelTitle}>
                                <Text style={styles.becameModelTitleText}>社群标签</Text>
                            </View>
                            <View style={styles.activityMemberWrap}>
                                <TextInput
                                    placeholder="例如桌游达人"
                                    value={currentTag}
                                    onChangeText={(val) => setCurrentTag(val)}
                                />
                            </View>
                            <View style={styles.becameFootWrap}>
                                <TouchableOpacity onPress={() => setShowSelectTag(false)}>
                                    <View style={styles.cancelBtn}>
                                        <Text style={styles.cancelBtnText}>取消</Text>
                                    </View>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={pushTag}>
                                    <View style={styles.okBtn}>
                                        <Text style={styles.okBtnText}>确认</Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </TouchableOpacity>

                </Modal>

                <SingleOickerModal
                    visible={showActivityType}
                    title={"活动类型"}
                    isOne={true}
                    onCancel={() => {
                        resetSelectTypeAll()
                        setShowActivityType(false)
                    }}
                    options={typeList}
                    onChange={(val, index) => {
                        dispatch(setActivityTypeObj({ activityTypeObj: { val, index } }))
                        setSelectActivityType(val);
                        setSelectTypeIndex(index);
                    }}
                    value={selectActivityType}
                    onConfirm={() => {
                        setShowActivityType(false)
                    }}
                />

                <Modal
                    visible={showSearchModal}
                    transparent={true}
                    animationType="slide"
                    // onRequestClose={onClose}
                >
                    <View style={styles.overlay}>
                        <View style={styles.modalContainer}>
                            {/* 顶部标题栏 */}
                            <View style={styles.header}>
                                <TouchableOpacity onPress={() => setShowSearchModal(false)}>
                                    <Text style={styles.cancelText}>取消</Text>
                                </TouchableOpacity>
                                <Text style={styles.title}>社群地址</Text>
                                <TouchableOpacity onPress={() => {
                                    setShowSearchModal(false)
                                    if (activeAdress == 0) {
                                        dispatch(setRegisterGroupData({ currentLocation: cityList[0] }))
                                    };
                                }}>
                                    <Text style={styles.confirmText}>确认</Text>
                                </TouchableOpacity>
                            </View>

                            {/* 搜索框 */}
                            <View style={styles.searchContainer}>
                                <View style={styles.searchWrap}>
                                    <View style={styles.searchIcon}>
                                        <Image source={searchIcon}  style={{ width: "100%", height: "100%" }} />
                                    </View>
                                    <TextInput
                                        ref={searchInptRef}
                                        style={styles.searchInput}
                                        placeholder="请输入搜索内容"
                                        onChangeText={searchByKeyword}
                                        onFocus={(val) => setIsVisialMap(false)}
                                        onBlur={(val) => setIsVisialMap(true)}
                                    />
                                    <TouchableOpacity onPress={searchByTitle} style={styles.searchBtn}>
                                        <Text style={styles.searchBtnText}>搜索</Text>
                                    </TouchableOpacity>
                                </View>

                                {/*{*/}
                                {/*    isVisialMap == false && (*/}
                                {/*        <TouchableOpacity onPress={() => blurSearchInp()}>*/}
                                {/*            <View style={styles.cancel}>*/}
                                {/*                <Text style={styles.cancelTexts}>取消</Text>*/}
                                {/*            </View>*/}
                                {/*        </TouchableOpacity>*/}
                                {/*    )*/}
                                {/*}*/}
                            </View>
                            {
                                (
                                    <View style={{ height: 200, width: "100%", backgroundColor: "red" }}>
                                        <MapView
                                            style={{ width: "100%", height: 200 }}
                                            region={region}
                                            onRegionChange={(newRegion) => {
                                                setRegion(newRegion)
                                                // getMapByTitleRequest()
                                                console.log('newRegion', newRegion);
                                            }}
                                            key={mapKey}
                                        >
                                            <Marker
                                                coordinate={region}
                                                title="北京"
                                                description="天安门"
                                            />
                                        </MapView>
                                    </View>
                                )
                            }


                            <View style={{ height: 350, paddingHorizontal: 12, }}>
                                <FlatList
                                    data={cityList}
                                    renderItem={cityReaderItem}
                                    style={{ height: 350 }}
                                    showsVerticalScrollIndicator={false}  // 隐藏垂直滚动条
                                    showsHorizontalScrollIndicator={false} // 隐藏水平滚动条（如果有）
                                />
                            </View>
                        </View>
                    </View>
                </Modal>

            </KeyboardAwareScrollView>
        </View>

    );
}

const styles = StyleSheet.create({
    scrollView: {
        flex: 1,
    },
    scrollViewContent: {
        padding: 0,
    },
    registerGroupContainer: {
        padding: 12,
    },
    registerGroupInfo: {
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: "#fff",
        paddingVertical: 8,
        paddingHorizontal: 12,
        borderRadius: 10,
    },
    avatorGroup: {
        width: 48,
        height: 48,
        backgroundColor: "#F7F8F9",
        borderRadius: 50,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    addIcon: {
        width: 14,
        height: 14,
    },
    registerHeaderSetting: {
        flexDirection: "row",
        alignItems: "center",
    },
    settingTitle: {
        color: "#9C9EAC"
    },
    registerContent: {
        backgroundColor:"#fff",
        paddingHorizontal: 12,
        marginTop: 12,
        borderRadius: 10,
    },
    registerItem: {
        flexDirection: "row",
        justifyContent: "space-between",
        borderBottomWidth: 0.3,
        borderBottomColor: "#E4E6EC",
        paddingVertical: 12,
    },
    registerItemContainer: {
        borderBottomWidth: 0.3,
        borderBottomColor: "#E4E6EC",
        paddingVertical: 12,
    },
    registerInputTextWrap: {
        backgroundColor: "#fff",
        borderRadius: 10,
        padding: 12,
        marginTop: 10,
    },
    resisterInputTextItem: {
        marginBottom: 24,
    },
    resisterInputTextItemText: {
        backgroundColor: "#F7F8F9",
        height: 100,
        paddingHorizontal: 12,
        paddingVertical: 6,
        borderRadius: 6,
        marginTop: 10,
    },
    footerBtnWrap: {
        backgroundColor: "#fff",
        flexDirection: "row",
        justifyContent: "center",
        paddingTop: 12,
        paddingBottom: 23,
    },
    footerBtn: {
        width: scaleSize(351),
        height: 38,
        backgroundColor: "#E4E6EC",
        borderRadius: 19,
        flexDirection: "row",
        justifyContent: 'center',
        alignItems: "center"
    },
    footerBtnText: {
        color: "#fff",
    },

    footerBtnWrapActive: {
        backgroundColor: "#fff",
        flexDirection: "row",
        justifyContent: "center",
        paddingTop: 12,
        paddingBottom: 23,
    },
    footerBtnActive: {
        width: scaleSize(351),
        height: 38,
        backgroundColor: "#EC6138",
        borderRadius: 19,
        flexDirection: "row",
        justifyContent: 'center',
        alignItems: "center"
    },
    footerBtnTextActive: {
        color: "#fff",
    },
    groupImage: {
        width: 82,
        height: 82,
        backgroundColor: "#F7F8F9",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginTop: 10,
    },
    tagText: {
        color: "#9C9EAC",
        fontSize: 12,
    },
    registerTagWrap: {
        flexDirection: "row",
        justifyContent: "space-between"
    },
    tagList: {
        flexDirection: "row",
        marginTop: 10,
    },
    tagListItem: {
        backgroundColor: 'rgba(255,70,0,0.1)',
        borderRadius: 8,
        paddingVertical: 2,
        paddingHorizontal: 6,
        marginRight: 10,
    },
    tagListItemText: {
        fontSize: 10,
        color: "#FB5313"
    },
    CoverImgWrap: {
        width: 48,
        height: 48,
        borderRadius: 25,
    },
    selectItem: {
        flexDirection: "row",
        alignItems: "center",
    },
    selectItemText: {
        fontSize: 14,
        color: "#9C9EAC"
    },
    becameModelContainer: {
        backgroundColor: 'rgba(0,0,0, 0.7)',
        height: "100%",
    },
    becameModelWrap: {
        width: scaleSize(296),
        // height: scaleSize(270),
        backgroundColor: "#fff",
        margin: "auto",
        borderRadius: 8,
        paddingTop: 24,
        paddingLeft: 18,
        paddingRight: 18,
        paddingBottom: 20,
        position: "relative",
        zIndex: 9,
    },
    becameModelTitle: {
        marginBottom: 14,
    },
    becameModelTitleText: {
        textAlign: "center",
        fontSize: 16,
        // fontWeight: "bold"
        // color: "#2A2B30"
    },
    becameFootWrap: {
        // marginTop: 58,
        flexDirection: "row",
        justifyContent: "space-between",
        paddingLeft: 10,
        paddingRight: 10,
    },
    cancelBtn: {
        backgroundColor: "#F7F8F9",
        width: 114,
        height: 38,
        borderRadius: 19,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    cancelBtnText: {
        // fontWeight: "bold",
    },
    okBtnText: {
        color: "#fff",
        fontWeight: "bold",
    },
    okBtn: {
        backgroundColor: "#EC6138",
        width: 114,
        height: 38,
        borderRadius: 19,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    activityMemberWrap: {
        flexDirection: "row",
        alignItems: "center",
        height: 36,
        width: "100%",
        backgroundColor: "#F7F8F9",
        borderRadius: 17,
        paddingHorizontal: 12,
        marginBottom: 24
    },
    overlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'flex-end',
    },
    modalContainer: {
        backgroundColor: '#fff',
        borderTopLeftRadius: 10,
        borderTopRightRadius: 10,
        paddingBottom: 20,
        maxHeight: '80%',
    },
    header: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 15,
        // borderBottomWidth: 1,
        // borderBottomColor: '#ddd',
    },
    title: {
        fontSize: 14,
        fontWeight: 'bold',
    },
    cancelText: {
        color: '#333333',
    },
    confirmText: {
        color: '#EC6138',
    },
    searchInput: {
        flex:1
    },
    content: {
        // paddingHorizontal: 15,
    },
    searchContainer: {
        flexDirection: "row",
        alignItems: "center"
        // margin: 15,
        // padding: 10,
        // borderRadius: 18,
        // backgroundColor: "#F7F8F9",
        // paddingLeft: 12,
    },
    searchWrap: {
        flexDirection: "row",
        alignItems: "center",
        margin: 15,
        // padding: 10,
        borderRadius: 18,
        backgroundColor: "#F7F8F9",
        paddingLeft: 12,
        flex: 1,
        // marginRight: 30,
    },
    cancel: {},
    cancelTexts: {
        fontSize: 14,
        color: "#333333",
        marginRight: 12,
    },
    locationItem: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        paddingVertical: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#ddd',
    },
    adressIcon: {
        width: 14,
        height: 14,
    },
    locationTitle: {
        fontSize: 14,
        color: "#2A2B30",
        fontWeight: '500',
        marginBottom: 8,
    },
    locationDescription: {
        fontSize: 12,
        color: '#888',
        marginBottom: 4,
    },
    searchIcon: {
        width: 12,
        height: 12,
        marginRight: 4,
    },
    searchBtn: {
        paddingVertical: 9,
        paddingHorizontal: 14,
        borderRadius: 19,
        backgroundColor: "#EC6138",
        // marginRight: 14,
    },
    searchBtnText: {
        color: '#fff',
        fontSize: 16,
    },
    addPicContainer: {
        marginTop: 12,
        flexDirection: "row",
        justifyContent: "space-between",
        flexWrap: "wrap"
    },
    addPic: {
        width: 82,
        height: 82,
        backgroundColor: "#F7F8F9",
        position: "relative",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginRight: 10,
    },
    addIcon: {
        width: 16,
        height: 16,
    },
    imgCloseWrap: {
        position: "absolute",
        right: 0,
        top: 0,
        width: 15,
        height: 15,
        zIndex: 10
    },
});
